package entity.gui;

import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Vector;

import static java.awt.event.KeyEvent.VK_ESCAPE;
import static java.nio.file.Files.newDirectoryStream;
import static javax.swing.JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT;

public class FileSelectorDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JComboBox<String> fileSelectorBox;
    private AttributeEditorForm form;

    public static final String DIR = "..\\heroes-village\\core-village\\src\\main\\resources";

    public FileSelectorDialog() {
        contentPane = new JPanel();

        buttonCancel = new JButton();
        buttonCancel.setText("Cancel");

        buttonOK = new JButton();
        buttonOK.setText("OK");
        fileSelectorBox = new JComboBox<>();
        contentPane.add(fileSelectorBox);
        contentPane.add(buttonCancel);
        contentPane.add(buttonOK);

        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(e -> onOK());

        buttonCancel.addActionListener(e -> onCancel());

        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(VK_ESCAPE, 0),
                WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        form = new AttributeEditorForm();
        form.initFrame();

    }

    private void onOK() {
        setVisible(false);

        form.setFilePath(Paths.get(DIR, fileSelectorBox.getSelectedItem().toString()));
        form.getFrame().setVisible(true);
    }

    private void onCancel() {
        dispose();
    }

    public static void main(String[] args) {
        FileSelectorDialog dialog = new FileSelectorDialog();
        ComboBoxModel<String> files = new DefaultComboBoxModel<>(dialog.paths(DIR));
        dialog.fileSelectorBox.setModel(files);
        dialog.pack();
        dialog.setVisible(true);
    }

    @Override public JPanel getContentPane() {
        return contentPane;
    }


    public Vector<String> paths(String templateDir) {
        try {
            Vector<String> paths = new Vector<>();
            try (DirectoryStream<Path> stream = newDirectoryStream(Paths.get(templateDir),
                    p -> p.getFileName().toString().endsWith(".yml"))) {
                stream.forEach(p -> paths.add(p.getFileName().toString()));
                return paths;
            }
        } catch (IOException e) {
            throw new RuntimeException("Something bad", e);
        }
    }
}
